<template>
  <!-- 添加商品组件 -->
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"> </el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeIndex - 0" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 标签页 -->
      <el-form :model="addGoodsForm" :rules="goodsRules" ref="addGoodsFormRef" label-position="top">
        <el-tabs tab-position="left" v-model="activeIndex" :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <!-- 基本信息 标签页 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                :options="cateList"
                clearable
                :props="cascaderProps"
                v-model="addGoodsForm.goods_cat"
                @change="cateChanged"
                style="width:400px"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 标签页 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyAttrList" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(attrVal, index) in item.attr_vals" :key="index" :label="attrVal" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性 标签页 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyAttrList" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片 标签页 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :headers="headersObj"
              list-type="picture"
              multiple
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <!-- 商品内容 标签页 -->
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
            <!-- 添加商品按钮 -->
            <el-button type="primary" class="btnAddGoods" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" :visible.sync="previewDialogVisible" width="50%" :before-close="handlePreviewClose">
      <el-image style="width: 100%" :src="previewPath"></el-image>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeIndex: '0',
      // 添加商品表单数据
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        attrs: [],
        // 上传图片的临时路径
        pics: [],
        // 商品介绍
        goods_introduce: ''
      },
      // 商品分类列表
      cateList: [],
      cascaderProps: {
        expandTrigger: 'hover',
        // 选择任意一级
        checkStrictly: true,
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 选中的父级分类的id数组
      // selectedKeys: [],
      // 添加商品表单数据验证规则
      goodsRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
        ],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请输入商品分类', trigger: 'blur' }]
      },
      // 动态参数列表数据
      manyAttrList: [],
      // 静态属性列表数据
      onlyAttrList: [],
      // 图片上传地址
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传组件的请求头对象
      headersObj: {
        Authorization: window.window.sessionStorage.getItem('token')
      },
      // 图片预览路径
      previewPath: '',
      // 控制图片预览对话框的显示
      previewDialogVisible: false
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories', { params: { type: 3 } })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },
    // 获取分类参数列表
    async getAttrs(type) {
      const { data: res } = await this.$http.get(`categories/${this.addGoodsForm.goods_cat[2]}/attributes`, {
        params: { sel: type }
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      if (type === 'many') {
        this.manyAttrList = res.data
        this.manyAttrList.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
      } else {
        this.onlyAttrList = res.data
      }
    },
    // 监听商品分类级联选择器 选中项改变事件
    cateChanged() {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
      }
    },
    // 标签页切换回调函数
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
      return true
    },
    // tab 被选中时触发
    tabClicked() {
      console.log('tabClicked: ')
      if (this.activeIndex === '1') {
        this.getAttrs('many')
        console.log(this.manyAttrList)
      } else if (this.activeIndex === '2') {
        this.getAttrs('only')
        console.log(this.onlyAttrList)
      }
    },
    // 处理图片预览效果
    handlePreview(file) {
      console.log('预览:')
      console.log(file)
      this.previewPath = file.response.data.url
      this.previewDialogVisible = true
    },
    // 处理图片删除操作
    handleRemove(file) {
      // 1. 获取将要删除的图片的临时路径
      const filePath = file.response.data.tmp_path
      // 2. 从pics数组中,找到图片对应的索引值
      this.addGoodsForm.pics.forEach((item, i) => {
        // 3. 调用数组的splice方法删除该图片对象
        if (item.pic === filePath) {
          this.addGoodsForm.pics.splice(i, 1)
        }
      })
    },
    // 监听图片上传成功的事件
    handleSuccess(response) {
      // 1.拼接得到图片信息对象
      const picInfo = {
        pic: response.data.tmp_path
      }
      // 2.将图片信息对象push到pics数组中
      this.addGoodsForm.pics.push(picInfo)
    },
    // 监听对话框关闭事件
    handlePreviewClose() {
      this.previewPath = ''
      this.previewDialogVisible = false
    },
    // 添加商品
    addGoods() {
      this.$refs.addGoodsFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('商品信息填写不完整, 请重新填写!')
        }
        // 执行添加业务逻辑
        // 1.处理 goods_cat
        this.addGoodsForm.goods_cat = this.addGoodsForm.goods_cat.join(',')
        // 2.处理 attrs
        this.manyAttrList.forEach(manyAttr => {
          const attr = {
            attr_id: manyAttr.attr_id,
            attr_value: manyAttr.attr_vals.join(' ')
          }
          this.addGoodsForm.attrs.push(attr)
        })
        this.onlyAttrList.forEach(onlyAttr => {
          const attr = {
            attr_id: onlyAttr.attr_id,
            attr_value: onlyAttr.attr_vals
          }
          this.addGoodsForm.attrs.push(attr)
        })
        const { data: res } = await this.$http.post('goods', this.addGoodsForm)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.$refs.addGoodsFormRef.resetFields()
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.btnAddGoods {
  margin-top: 20px;
}
</style>
